package org.example.day12;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 5.1.2.5: Timer类的 cancel方法
 *      作用: 和TimerTask的cancel方法不同(仅从任务队列中删除自己)，Timer#cancel()作用是将任务队列中所有的task清除.
 */
public class MyThread12 {
    private static Timer timer = new Timer();
    static public class MyTaskA extends TimerTask{
        @Override
        public void run() {
            System.out.println("A运行了！ 时间为: " + new Date());
            timer.cancel();
        }
    }
    static public class MyTaskB extends TimerTask{
        @Override
        public void run() {
            System.out.println("B运行了！ 时间为: " + new Date());
        }
    }

    public static void main(String[] args) {
        try {
            MyTaskA taskA = new MyTaskA();
            MyTaskB taskB = new MyTaskB();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString1 = "2022-05-16 11:09:00";
            Date dateRef = sdf.parse(dateString1);
            System.out.println("字符串时间为: " + dateRef.toLocaleString() + " 当前时间: " + new Date().toLocaleString());
            timer.schedule(taskA,dateRef,4000);
            timer.schedule(taskB,dateRef,4000);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
